package com.duke.shaking.profile;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;

import com.androidquery.AQuery;
import com.duke.shaking.R;
import com.duke.shaking.TitleActivity;
import com.duke.shaking.interaction.ChatActivity;
import com.duke.shaking.net.AsyncHttpResponseWithResultHandler;
import com.duke.shaking.net.NetUtils;
import com.duke.shaking.pojo.ChatFriend;
import com.duke.shaking.pojo.User;
import com.duke.shaking.pojo.UserImage;
import com.duke.shaking.widget.PhotoMgrGridAdapter;
import com.duke.shaking.widget.PhotoMgrGridView;

public class FriendPhotosActivity extends TitleActivity {
	
	private ChatFriend friend;
	private boolean isNewFriend;
	private AQuery aQuery;
	private PhotoMgrGridView photoGridView;
	private Context context;
	
	public FriendPhotosActivity() {
		super();
		this.aQuery = new AQuery(this);
	}

	@Override
	protected int getLayoutId() {
		// TODO Auto-generated method stub
		return R.layout.activity_friend_photos;
	}

	@Override
	protected void onTitleInit() {
		// TODO Auto-generated method stub
		initTitle(TITLE_BTN_EXIST | TITLE_BTN_BACK,
				R.string.back,
				0, //isNewFriend ? TITLE_BTN_EXIST : 0,
				0, //isNewFriend ? R.string.say_hello : 0,
				R.string.title_view_photos);
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		friend = (ChatFriend)getIntent().getSerializableExtra("friend");
        isNewFriend = getIntent().getBooleanExtra("isNewFriend", false);
        
		super.onCreate(savedInstanceState);
		context = getApplicationContext();
        
        photoGridView = (PhotoMgrGridView)this.findViewById(R.id.photoGridView);
        photoGridView.setEditable(false);
        
        photoGridView.setOnItemClickListener(new OnItemClickListener() {

        	public void onItemClick(AdapterView<?> parent, View view, int position,
        			long id) {
        		// launch gallery activity to view all photos
        		Intent i = new Intent(context, ViewPhotosPagerActivity.class);
        		i.putExtra(ViewPhotosPagerActivity.EXTRA_IMAGES, photoGridView.getPhotos());
        		i.putExtra(ViewPhotosPagerActivity.EXTRA_POSITION, position);
        		startActivity(i);
        	}
        });

        initData();
        initPhotos();
	}
	
	private void initData() {
		AsyncHttpResponseWithResultHandler responseHandler = new AsyncHttpResponseWithResultHandler(){
			
        	@Override
			public void onResultSuccess(String response) {
				super.onResultSuccess(response);
				
				JSONObject jsonObj = this.getBody(response);
				showInfo(jsonObj);
			}

			@Override
			public void onResultFailure(String result) {
				super.onResultFailure(result);
			}
        };
        
        if (friend.getAvatarUrl() != null
        	&& friend.getAge() != null
        	&& friend.getNickname() != null
        	&& friend.getCity1() != null) {
        	showInfo(friend.getAvatarUrl(),
        			friend.getNickname(),
        			friend.getAge(),
        			friend.getCity1());
        }
        else {
        	NetUtils.getFriendInfo(this, responseHandler, friend.getUserId());
        }
	}
	
	private void showInfo(JSONObject jsonObj) {
		String avatarUrl = jsonObj.optString("photo");
		String nickname = jsonObj.optString("nickname");
		int age = jsonObj.optInt("age", 0);
		String city = jsonObj.optString("city_1");
		showInfo(avatarUrl, nickname, age, city);
	}
	
	private void showInfo(String avatarUrl, String nickname, int age, String city) {
		
		if(avatarUrl != null && !avatarUrl.trim().equals("")) {
			aQuery.id(R.id.avatar).image(avatarUrl, false, true, 0, R.drawable.blank_avatar);
		}
		
		if(nickname != null && !nickname.trim().equals("")) {
			aQuery.id(R.id.txt_nickname).text(nickname);
		}
		
		if(age != 0) {
			aQuery.id(R.id.txt_age).text(String.valueOf(age) + getString(R.string.age_year));
		}
		
		if(city != null && !city.trim().equals("")) {
			String sex = "";
			if (friend.getSex() != null) {
				if (friend.getSex() == User.sex_male) {
					sex = getString(R.string.single_male);
				} else if (friend.getSex() == User.sex_female) {
					sex = getString(R.string.single_female);
				}
			}
			aQuery.id(R.id.txt_local).text(city + sex);
		}
	}
	
	private void initPhotos() {
		AsyncHttpResponseWithResultHandler responseHandler = new AsyncHttpResponseWithResultHandler(){
			
        	@Override
			public void onResultSuccess(String response) {
				super.onResultSuccess(response);
				
				JSONObject jsonBody = getBody(response);
				if(jsonBody != null) {
					try {
						JSONArray photos = jsonBody.optJSONArray("photo");
						if (photos != null && photos.length() > 0) {
							List<UserImage> imgList = new ArrayList<UserImage>();
							for(int i = 0; i < photos.length(); i ++) {
								String pid = photos.getJSONObject(i).optString("pid");
								String url = photos.getJSONObject(i).optString("url");
								String url_1 = photos.getJSONObject(i).optString("urlm");
								imgList.add(new UserImage(url, url_1, pid));
							}
							photoGridView.addPhotos(imgList);
							updatePhotos();
						}
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}

        	@Override
        	public void onResultFailure(String result) {
        		super.onResultFailure(result);

        	}
		};


		Map<String, String> params = new HashMap<String, String>();
		params.put(NetUtils.TOKEN, me.getAuthToken());
		params.put(NetUtils.FUID, friend.getUserId());
		NetUtils.getPhotos(this, responseHandler, params);
	}

	@Override
	public void onLeftBtn(View v) {
		// TODO Auto-generated method stub
		super.onLeftBtn(v);
	}

	@Override
	public void onRightBtn(View v) {
		go(ChatActivity.class, "friend", friend);
	}
	
	public void updatePhotos() {
		photoGridView.updateHeight();
		((PhotoMgrGridAdapter)photoGridView.getAdapter()).notifyDataSetChanged();
	}
}
